package com.authapi.sample.api.utils;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class PageUtil {
    // 定义请求头中存放页码索引的键名，可根据实际约定修改
    private static final String PAGE_INDEX_HEADER_KEY = "pageIndex";
    // 定义请求头中存放每页数量的键名，同样可按约定调整
    private static final String PAGE_SIZE_HEADER_KEY = "pageSize";

    /**
     * 从HttpServletRequest的header中获取pageIndex的值
     * @return 解析得到的pageIndex，若获取失败或解析异常则返回默认值（这里假设默认值为1）
     */
    public static int getPageIndexFromHeader() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String pageIndexStr = request.getHeader(PAGE_INDEX_HEADER_KEY);
        try {
            return Integer.parseInt(pageIndexStr);
        } catch (NumberFormatException e) {
            // 如果解析失败，返回默认值1，表示第一页
            return 1;
        }
    }

    /**
     * 从HttpServletRequest的header中获取pagesize的值
     * @return 解析得到的pagesize，若获取失败或解析异常则返回默认值（这里假设默认值为10）
     */
    public static int getPageSizeFromHeader() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String pagesizeStr = request.getHeader(PAGE_SIZE_HEADER_KEY);
        try {
            return Integer.parseInt(pagesizeStr);
        } catch (NumberFormatException e) {
            // 如果解析失败，返回默认值10，表示每页10条数据
            return 5;
        }
    }
}
